package client

import (
	"context"
	"google.golang.org/grpc"
	"week62/common/proto/user"
)

type Handler func(ctx context.Context, client user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8080", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := user.NewUserClient(dial)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	defer dial.Close()
	return res, nil
}

func Login(ctx context.Context, req *user.LoginReq) (*user.LoginResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.Login(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.LoginResp), nil
}

func SendSms(ctx context.Context, req *user.SendSmsReq) (*user.SendSmsResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.SendSms(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.SendSmsResp), nil
}

func AddOrder(ctx context.Context, req *user.AddOrderReq) (*user.AddOrderResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.AddOrder(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.AddOrderResp), nil
}

func SyncGoods(ctx context.Context, req *user.SyncGoodsReq) (*user.SyncGoodsResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.SyncGoods(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.SyncGoodsResp), nil
}
